package com.travelranking.view;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import org.apache.commons.lang.StringUtils;

import com.travelranking.pojo.City;
import com.travelranking.service.CityService;

public class CityAction {
	private City city;
	private CityService service;

	public CityAction() {
		city = new City();
	}

	public String add() {
		if (validateFields()) {
			service.add(city);
			return "LIST";
		}
		return "NEWCITY";
	}

	public List<SelectItem> getListCity() {
		List<SelectItem> result = new ArrayList<SelectItem>();
		for (City city : service.list()){
			result.add(new SelectItem(city.getId(),city.getName()));
		}
		return result;
	}

	public String cleanFields() {
		city = new City();
		return "NEWCITY";
	}

	public String cleanAndList() {
		city = new City();
		return "LIST";
	}

	public City getCity() {
		return city;
	}

	public void setCity(City city) {
		this.city = city;
	}

	/*
	 * metodos de acesso e auxiliares
	 */
	public CityService getService() {
		return service;
	}

	public void setService(CityService service) {
		this.service = service;
	}

	private boolean validateFields() {
		boolean result = true;

		if (StringUtils.isEmpty(city.getName())) {
			addFacesMessage("Nome da cidade deve ser informado.");
			result = false;
		}
		if ((city.getCountry() == null) || (city.getCountry().getId() == null)
				|| (city.getCountry().getId() == 0)) {
			addFacesMessage("País deve ser informado.");
			result = false;
		}
		return result;
	}

	public void addFacesMessage(String s) {
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, s, s);
		FacesContext cont = FacesContext.getCurrentInstance();
		cont.addMessage(null, msg);
	}
}
